//
//  watchingRecordsVC.m
//  WuyouTang
//
//  Created by IOS1 on 2019/7/5.
//  Copyright © 2019 cat. All rights reserved.
//

#import "watchingRecordsVC.h"
#import "WatchRecordListCell.h"
#import "YBGetVideoObj.h"

@interface watchingRecordsVC ()<UITableViewDelegate,UITableViewDataSource>{
    UITableView *listTable;
    NSMutableArray *listArray;
    int page;
    BOOL _currentEditeState;
    NSMutableArray *_flagDel;
    NSMutableArray *_delVideo;
    BOOL _singleDel;
}

@end

@implementation watchingRecordsVC



- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = RGB_COLOR(@"#110D24", 1);
    
    self.titleL.text = YZMsg(@"观看记录");
    
    page = 1;
    listArray = [NSMutableArray array];

    _flagDel = [NSMutableArray array];
    _delVideo = [NSMutableArray array];
    _currentEditeState = NO;
    self.rightBtn.hidden = NO;
    [self.rightBtn setTitle:YZMsg(@"管理") forState:0];
    self.rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 6);
    [self.rightBtn setTitleColor:RGB_COLOR(@"#ffffff", 1) forState:0];
    
    [self creatUI];
    [self requestData];

}
- (void)creatUI{
    listTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight) style:0];
    listTable.delegate = self;
    listTable.dataSource = self;
    listTable.backgroundColor = Normal_Color;
    listTable.separatorStyle = 0;
    [self.view addSubview:listTable];
    //MJRefreshHeader
    listTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page = 1;
        [self requestData];
    }];
    //MJRefreshBackFooter
    listTable.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        page ++;
        [self requestData];
    }];

}
- (void)requestData{
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Video.GetViewRecord" Dic:@{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"p":@(page)} Suc:^(int code, id info, NSString *msg) {
        [listTable.mj_header endRefreshing];
        [listTable.mj_footer endRefreshing];
        if (code == 0) {
            NSArray *list = [NSArray arrayWithArray:info];
            if (page == 1) {
                [listArray removeAllObjects];
            }
            [listArray addObjectsFromArray:list];
            [weakSelf resetDelFlag];
            _currentEditeState = NO;
        }
        [listTable reloadData];
    } Fail:^(id fail) {
        [listTable.mj_header endRefreshing];
        [listTable.mj_footer endRefreshing];
    }];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WatchRecordListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WatchRecordListCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"WatchRecordListCell" owner:nil options:nil] lastObject];
    }
    NSDictionary *subdic = listArray[indexPath.row];
    cell.dataDic = subdic;
    cell.backgroundColor = CellRow_Cor;
    cell.contentView.backgroundColor = CellRow_Cor;
    cell.selectionStyle = 0;
    if (_currentEditeState == NO) {
        cell.flagWidth.constant = 0;
        cell.thumbLeft.constant = 0;
    }else {
        cell.flagWidth.constant = 18;
        cell.thumbLeft.constant = 8;
    }
    NSString *flagStr = _flagDel[indexPath.row];
    if ([flagStr isEqual:@"1"]) {
        cell.falgIV.image = [UIImage imageNamed:@"下一步"];
    }else {
        cell.falgIV.image = [UIImage imageNamed:@"编辑-圈圈"];
    }

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSDictionary *subDic = listArray[indexPath.row];
    if (_currentEditeState) {
        //编辑
        NSString *flagStr = _flagDel[indexPath.row];
        if ([flagStr isEqual:@"1"]) {
            //取消选中
            [_flagDel replaceObjectAtIndex:indexPath.row withObject:@"0"];
            [_delVideo removeObject:subDic];
        }else {
            //选中
            [_flagDel replaceObjectAtIndex:indexPath.row withObject:@"1"];
            [_delVideo addObject:subDic];
        }
        [self changeRigthTitle];
        [tableView reloadData];
        
    }else {
        //观看
        [self goWatchVideo:indexPath];
    }
    
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    YBWeakSelf;
    UITableViewRowAction *delAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:YZMsg(@"删除") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        //NSLog(@"====del");
        _singleDel = YES;
        NSDictionary *subDic = listArray[indexPath.row];
        [_delVideo addObject:subDic];
        [weakSelf showDelAlert];
    }];
    delAction.backgroundColor = Pink_Cor;
    return @[delAction];
}
-(void)goWatchVideo:(NSIndexPath *)indexPath {
    NSString *vidoeID = minstr([listArray[indexPath.row] valueForKey:@"id"]);
    [YBGetVideoObj lookManeger].fromWhere = @"watchingRecordsVC";
    [YBGetVideoObj lookManeger].videoID = vidoeID;
    [YBGetVideoObj lookManeger].playIndex = (int)indexPath.row;
    [YBGetVideoObj lookManeger].videoList = [listArray mutableCopy];
    [YBGetVideoObj lookManeger].paging = page;
    [YBGetVideoObj lookManeger].baseUrl = @"Video.getViewRecord";
    [[YBGetVideoObj lookManeger]goLookVC];
}
-(void)changeRigthTitle {
    BOOL haveSelDel = [self selDelVideo];
    if (haveSelDel) {
        [self.rightBtn setTitle:YZMsg(@"删除") forState:0];
    }else {
        [self.rightBtn setTitle:YZMsg(@"管理") forState:0];
    }
}
-(void)resetDelFlag {
    [_flagDel removeAllObjects];
    for (int i=0; i<listArray.count; i++) {
        [_flagDel addObject:@"0"];
    }
    [_delVideo removeAllObjects];
    [self changeRigthTitle];
}
-(BOOL)selDelVideo {
    BOOL haveSelDel = NO;
    for (NSString *delFlag in _flagDel) {
        if ([delFlag isEqual:@"1"]) {
            haveSelDel = YES;
            break;
        }
    }
    return haveSelDel;
}
- (void)clickNaviRightBtn {
   
    BOOL haveSelDel = [self selDelVideo];
    if (haveSelDel) {
        _singleDel = NO;
        [self showDelAlert];
    }else {
        //没选中 就切换编辑状态
        _currentEditeState = !_currentEditeState;
        [listTable reloadData];
    }
    
}
-(void)sureDelSelVideo {
    NSString *idStrs = @"";
    for (NSDictionary *delDic in _delVideo) {
        idStrs = [idStrs stringByAppendingFormat:@"%@,",[delDic valueForKey:@"id"]];
    }
    YBWeakSelf;
    if (idStrs.length > 1) {
        //去掉最后一个逗号
        idStrs = [idStrs substringToIndex:[idStrs length] - 1];
        [MBProgressHUD showMessage:@""];
        [WYNetworking postWithUrl:@"Video.deltViewRecord" Dic:@{@"videoids":idStrs} Suc:^(int code, id info, NSString *msg) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:msg];
            if (code == 0) {
                [listArray removeObjectsInArray:_delVideo];
                //删除成功后
                [weakSelf resetDelFlag];
                _currentEditeState = NO;
                [listTable reloadData];
            }
        } Fail:^(id fail) {
            [MBProgressHUD hideHUD];
        }];
    }
    
}
-(void)showDelAlert{
    YBWeakSelf;
    NSString *msg = _singleDel?YZMsg(@"确定删除该条记录?"):YZMsg(@"确定删除所选观看记录?");
    NSDictionary *contentDic = @{@"title":@"",@"msg":msg,@"left":YZMsg(@"取消"),@"right":YZMsg(@"确定"),@"richImg":@""};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            //删除
            [weakSelf sureDelSelVideo];
        }else {
            //取消
            [weakSelf resetDelFlag];
            _currentEditeState = NO;
            [listTable reloadData];
        }
    }];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return !_currentEditeState;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
